package com.gimi.cloud.jimi.client.controller.userInfo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gimi.cloud.jimi.client.service.userInfo.MoreInfoLogService;
import com.gimi.cloud.jimi.client.service.userInfo.MoreInfoService;
import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.utils.JsonUtil;
import com.gimi.cloud.jimi.common.utils.StringUtil;
import com.gimi.cloud.jimi.common.utils.reqhead.Response;
import com.gimi.cloud.jimi.common.utils.reqhead.Util;
import com.gimi.cloud.jimi.commonService.InterfacePlatform.InterfacePlatformRequestService;
import com.gimi.cloud.jimi.dto.app.moreInfo.MoreInfoDTO;
import com.gimi.cloud.jimi.entity.app.moreInfo.MoreInfoLogEntity;
import com.gimi.cloud.jimi.dto.params.InterfaceCenterParams;
import com.gimi.cloud.jimi.dto.params.RdTaobaoParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@RestController
@RequestMapping("info/taobao")
public class RdTaobaoController {
    @Autowired
    private MoreInfoService moreInfoService;
    @Autowired
    private MoreInfoLogService moreInfoLogService;
    @Autowired
    private InterfacePlatformRequestService interfacePlatformRequestService;

    /**
     * 创建魔盒电商淘宝任务
     */
    @RequestMapping("/create")
    public void createTask(@RequestBody RdTaobaoParams taobao, HttpServletResponse response) {
        Response resp = new Response();
        InterfaceCenterParams requestParam = new InterfaceCenterParams("mohe_create_elec_task", "moheinterface");
        requestParam.addParam("realName", taobao.getRealName());
        requestParam.addParam("identityCode", taobao.getIdentityCode());
        requestParam.addParam("mobileNumber", taobao.getMobileNumber());
        requestParam.addParam("channelCode", "000103");
        requestParam.addParam("channelType", "DS");

        try {
            MoreInfoLogEntity log = new MoreInfoLogEntity();
            log.setRequestData(JsonUtil.toJson(requestParam));
            log.setAddTime(new Date());
            log.setRemark("创建魔盒电商淘宝任务");
            log.setUserId(taobao.getUserId());
            log.setType("2");
            String result = interfacePlatformRequestService.sendApiPost(JsonUtil.toJson(requestParam));
            log.setResponseData(result);
            log.setStatus(0);
            JSONObject json = JSON.parseObject(result);
            JSONObject jsonHead = json.getJSONObject("head");
            JSONObject jsonBody = json.getJSONObject("body");
            if(jsonBody != null) {
                String rCode = jsonBody.getString("code");
                if("0".equals(rCode)) {
                    String taskId = jsonBody.getString("task_id");
                    log.setStatus(1);
                    //taobao.setTaskId(taskId);
                    //taobaoService.saveTaobao(taobao);
                }
                moreInfoLogService.saveMoreInfoLog(log);
                resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
                resp.setRes_data(jsonBody);
                Util.sendResponse(JsonUtil.toJson(resp), response);
            } else {
                moreInfoLogService.saveMoreInfoLog(log);
                String message = jsonHead.getString("responseDescription");
                String code = jsonHead.getString("responseCode");
                resp.setRes_msg(message);
                resp.setRes_code(code);
                Util.sendResponse(JsonUtil.toJson(resp), response);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.setResponseCode(ResponseCodeEnum.UNKNOWN_ERROR);
            Util.sendResponse(JsonUtil.toJson(resp), response);
            return;
        }
    }

    /**
     * 电商登录验证
     * @param taobao
     * @param response
     */
    @RequestMapping("/valid")
    public void valid(@RequestBody RdTaobaoParams taobao, HttpServletResponse response) {
        Response resp = new Response();
        /*RdTaobaoDTO taobaoDTO = taobaoService.getNewestTaobaoByUser(taobao.getUserId());
        if(taobaoDTO == null) {
            resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
            Map<String, String> resMap = new HashMap<>();
            resMap.put("message", "请先完成信息认证");
            resMap.put("success","false");
            resp.setRes_data(resMap);
            Util.sendResponse(JsonUtil.toJson(resp), response);
            return;
        }*/

        InterfaceCenterParams param = new InterfaceCenterParams("mohe_login_valid","moheinterface");
        param.addParam("mobileNumber",taobao.getMobileNumber());
        param.addParam("taskId",taobao.getTaskId());
        param.addParam("mobilePassword", taobao.getMobilePassword());
        param.addParam("smsCode", taobao.getSmsCode());
        param.addParam("authCode", taobao.getAuthCode());
        param.addParam("loginType", "");
        param.addParam("channelCode", "000103");
        //如果为首次调用
        //请求类型。提交是"submit"，轮询是"query"。首先 用"submit"提交用户名和密码，然后用"query"查询，直到返回码 不是100。
        if("0".equals(taobao.getCode()) || StringUtil.isBlank(taobao.getTaskStage())) {
            param.addParam("taskStage","INIT");
            param.addParam("requestType", "submit");
            param.addParam("code", "0");
        } else {
            param.addParam("taskStage",taobao.getTaskStage());
            param.addParam("requestType", "query");
            param.addParam("code", "1");
        }

        MoreInfoLogEntity log = new MoreInfoLogEntity();
        log.setRequestData(JsonUtil.toJson(param));
        log.setRemark("创建魔盒电商淘宝任务");
        log.setUserId(taobao.getUserId());
        log.setAddTime(new Date());
        try {
            String result = interfacePlatformRequestService.sendApiPost(JsonUtil.toJson(param));
            log.setResponseData(result);
            JSONObject json = JSON.parseObject(result);
            JSONObject jsonHead = json.getJSONObject("head");
            JSONObject jsonBody = json.getJSONObject("body");
            if(jsonBody != null) {
                String code = jsonBody.getString("code");
                String message = jsonHead.getString("message");
                if ("137".equals(code)) {
                    //TODO 更新淘宝数据状态
                    MoreInfoDTO taobaoDTO = moreInfoService.getMoreInfoByUserIdAndType(taobao.getUserId(), "2");
                    if (taobaoDTO == null) {
                        taobaoDTO = new MoreInfoDTO();
                    }
                    taobaoDTO.setUserId(taobao.getUserId());
                    taobaoDTO.setDataType("2");
                    taobaoDTO.setReportData(taobao.getTaskId());
                    taobaoDTO.setGetdata("1");
                    moreInfoService.saveMoreInfoService(taobaoDTO);
                }
                resp.setRes_data(jsonBody);
            } else {
                resp.setRes_data(jsonHead);
            }
            resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        } catch (Exception e) {
            resp.setResponseCode(ResponseCodeEnum.FAILURE);
        }
        moreInfoLogService.saveMoreInfoLog(log);
        Util.sendResponse(JsonUtil.toJson(resp), response);
    }

}
